package com.vshop.timingtask;

import com.vshop.entity.alast.common.PartnerServicePlan;
import com.vshop.entity.alast.common.ServicePlanOrderRecord;
import com.vshop.entity.alast.linksentity.LinksOrdersPayment;
import com.vshop.service.task.ServicePlanTaskServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 内部定时任务程序：
 * <p>
 * 将Travis和 ISCETT的老的模式的订单数据
 * <p>
 * 从links的user_order_payment_manager_t表将订单数据
 * 同步到v-shop的service_plan_order_record_t表
 * <p>
 * http://localhost:8088/vshopSystem/syncOldOrder
 *
 * @author lm
 * @date 2020/8/10 11:44
 */

@Configuration
@EnableScheduling
@RestController
@Slf4j
public class OldOrderDataSyncTask {
    @Value("${system.autoTask}")
    private boolean autoTask;
    @Autowired
    ServicePlanTaskServiceImpl taskService;

    /**
     * 每天早上6点2分执行一次
     * <p>
     * 新套餐上架完毕才能迁移数据过来，到时候直接把sql语句改成获取全部，然后再改，先把and isSync ='1'去掉
     * <p>
     * select * FROM user_order_payment_manager_t
     * WHERE payRst ='success'
     * and isSync ='1'
     * and (orderId is not null or orderId !='') ;
     *
     * @author lm
     * @date 2020/8/10 14:43
     */

    @Scheduled(cron = "0 2 6 * * ?")
    @GetMapping(value = "syncOldOrderTask")
    @Async
    public void execute() {
        if (autoTask) {
            syncOldOrderTask();
        }
    }

    public void syncOldOrderTask() {

        log.info("每天早上6点执行SyncOldOrderDataTask任务开始执行！");

        List<LinksOrdersPayment> oldOrdersList = taskService.queryOrderPaymentList();

        if (oldOrdersList == null || oldOrdersList.isEmpty()) {
            log.info("每天早上6点执行SyncOldOrderDataTask任务无可同步的旧订单直接结束！");
            return;
        }

        for (LinksOrdersPayment orders : oldOrdersList) {

            try {

                List<PartnerServicePlan> servicePlanList = taskService.queryServicePlan(orders.getPartnerCode(), orders.getPackageCode());

                if (null != servicePlanList && !servicePlanList.isEmpty()) {

                    for (PartnerServicePlan servicePlan : servicePlanList) {

                        //1，先去把订单记录同步到v-shop的service_plan_order_record_t表：用原表中唯一的requestOrderId来做payId和orderNo
                        ServicePlanOrderRecord or = new ServicePlanOrderRecord();
                        or.setPayId(orders.getRequestOrderId());
                        or.setPayRst(orders.getPayRst());
                        or.setPayType("0");
                        or.setPayAccount("2");
                        or.setTransactionId(orders.getOrderId());
                        or.setRequestOrderId(orders.getRequestOrderId());
                        or.setDeviceCode(orders.getDeviceId());
                        or.setOrderNo(orders.getRequestOrderId());
                        or.setOrderId(orders.getOrderId());
                        or.setPartnerCode(orders.getPartnerCode());
                        or.setPartnerName(orders.getPartnerName());
                        or.setServicePlanShowName(servicePlan.getServicePlanShowName());
                        or.setServicePlanCode(servicePlan.getServicePlanCode());
                        or.setPackageName(orders.getPackageName());
                        or.setPackageCode(orders.getPackageCode());
                        or.setPackageType(orders.getPackageType());
                        or.setOrderPeriod(orders.getOrderPeriod());
                        or.setPayAmount(orders.getAmount());
                        or.setPayCurrency(orders.getOrderCurrency());
                        or.setPayUnit(orders.getAmount());
                        if ("USD".equalsIgnoreCase(orders.getOrderCurrency())) {
                            or.setSettlePrice(orders.getAmount());
                        } else {
                            float fee = Float.parseFloat(orders.getAmount());
                            or.setSettlePrice(String.format("%1.2f", fee / 7));
                        }
                        or.setIsPartnerNotice(orders.getIsChannelNotity());
                        or.setPayStatus("1");
                        or.setIsRequest("1");
                        or.setIsRenew("0");
                        or.setIsOpen("1");
                        if ("P000239".equals(orders.getPartnerCode())) {
                            or.setTerminal("1");
                        } else {
                            or.setTerminal("0");
                        }
                        or.setMark("0");
                        or.setCreateDate(orders.getCreateTime());
                        or.setPayResultDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orders.getCreateTime()));
                        or.setOrderResultDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orders.getCreateTime()));
                        taskService.syncData(or);
                    }
                }

                //2，然后回去告诉links的user_order_payment_manager_t表我收到记录了
                LinksOrdersPayment linksOrders = new LinksOrdersPayment();
                linksOrders.setRequestOrderId(orders.getRequestOrderId());
                linksOrders.setDeviceId(orders.getDeviceId());
                linksOrders.setOrderId(orders.getOrderId());
                linksOrders.setIsSync("0");
                taskService.updateLinksIsSync(linksOrders);

            } catch (Exception e) {
                log.info("每天早上6点执行SyncOldOrderDataTask任务捕获到异常：" + e);
                continue;
            }
        }
        log.info("每天早上6点执行SyncOldOrderDataTask任务结束：同步了：" + oldOrdersList.size() + "条");
    }

}
